package mju.cxf.controller.user;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mju.cxf.constant.MessageConstant;
import mju.cxf.context.BaseContext;
import mju.cxf.dto.SalesAfterDTO;
import mju.cxf.entity.Order;
import mju.cxf.entity.Sales;
import mju.cxf.entity.SalesAfter;
import mju.cxf.result.Result;
import mju.cxf.service.OrderService;
import mju.cxf.service.SalesAfterService;
import mju.cxf.service.SalesService;
import mju.cxf.service.impl.OrderServiceImpl;
import mju.cxf.service.impl.PhotoServiceImpl;
import mju.cxf.vo.SalesAfterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 售后相关接口
 */

@RestController
@RequestMapping("/user/api/saleAfter")
@Api(tags = "用户售后接口列表")
public class ISalesAfterController {
    @Autowired
    private SalesAfterService salesAfterService;
    @Autowired
    private PhotoServiceImpl photoService;
    @Autowired
    private OrderServiceImpl orderService;
    @Autowired
    private SalesService salesService;
    /**
     * 新增售后信息
     *
     * @return
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "新增售后信息")
    public Result<String> addSalesAfter(@RequestBody SalesAfterDTO salesAfterDTO) {
        final SalesAfter build = SalesAfter.builder()
                .number("XSSH" + System.currentTimeMillis())
                .orderNumber(salesAfterDTO.getOrderId())
                .imageUrls(JSON.toJSONString(salesAfterDTO.getImageUrl()))
                .remarks(salesAfterDTO.getRemark())
                .createUser(BaseContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .userId(BaseContext.getCurrentId())
                .type(salesAfterDTO.getTypeId())
                .build();
        //保存售后消息
        if (salesAfterService.save(build)) {
            //修改订单为纠纷中
            salesAfterDTO.getImageUrl().forEach(photoService::saveImages);
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getNumber,salesAfterDTO.getOrderId()).set(Order::getStatus,3);
            orderService.update(updateWrapper);
            //修改库存商品状态为纠纷中
            LambdaUpdateWrapper<Sales> suw = new LambdaUpdateWrapper<>();
            suw.in(Sales::getSalesNumber,salesAfterDTO.getCdKeys()).set(Sales::getState,5);
            salesService.update(suw);
            return Result.success(MessageConstant.SUCCESS_MESSAGE);
        }
        return Result.error(MessageConstant.FAILURE_MESSAGE);
    }

    @PostMapping("/cancel")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "取消售后信息")
    public Result<String> cancelSalesAfter(@RequestParam int salesAfterId) {
        final SalesAfter salesAfter = salesAfterService.getById(salesAfterId);
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getNumber,salesAfter.getOrderNumber()).set(Order::getStatus,1);
        orderService.update(updateWrapper);
        //修改库存商品状态为纠纷中
        LambdaUpdateWrapper<Sales> suw = new LambdaUpdateWrapper<>();
        suw.eq(Sales::getOrderNumber,salesAfter.getOrderNumber()).eq(Sales::getState,5).set(Sales::getState,4);
        salesService.update(suw);
        salesAfter.setStatus(3);
        return salesAfterService.updateById(salesAfter)?Result.success(MessageConstant.SUCCESS_MESSAGE):Result.error(MessageConstant.FAILURE_MESSAGE);
    }

    @PostMapping("/page")
    public Result<HashMap<String,Object>> orderAfterList(@RequestParam("page") int page,
                                          @RequestParam("size") int size){
        LambdaQueryWrapper<SalesAfter> queryWrapper = new LambdaQueryWrapper<>();
        //根据创建时间倒叙
        queryWrapper.eq(SalesAfter::getUserId, BaseContext.getCurrentId()).orderByDesc(SalesAfter::getCreateTime);
        Page<SalesAfter> page1 = salesAfterService.page(new Page<>(page, size), queryWrapper);
        HashMap<String,Object> map = new HashMap<>();
        map.put("orderAfterList", page1.getRecords());
        map.put("pages", page1.getPages());
        map.put("current", page1.getCurrent());
       return Result.success(map);
    }
}
